﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Castle.Services.Transaction;
using Meqs.Entity;
using Meqs.Logic.Interface;

namespace Meqs.Logic.Implement
{
    public class QuestionItemsLogic : CommonLogic<QuestionItems, int>, IQuestionItemsLogic
    {
        #region Implementation of ICommonLogic<QuestionItems, int>

        /// <sammury>
        /// 创建对象
        /// </sammury>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Create(QuestionItems entity)
        {
            return CreateObject(entity);
        }

        /// <sammury>
        /// 更新对象
        /// </sammury>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Update(QuestionItems entity)
        {
            return UpdateObject(entity);
        }

        /// <summary>
        /// 删除对象
        /// </summary>
        /// <param name="entityId"></param>
        /// <param name="schoolMark"></param>
        /// <returns></returns>
        public int Delete(int entityId, string schoolMark)
        {
            Hashtable ht = new Hashtable();
            ht.Add("RID", entityId);
            ht.Add("SchoolMark", schoolMark);
            return DeleteCustomer("QuestionItems.Delete", ht);
        }

        /// <summary>
        /// 删除所有对象
        /// </summary>
        /// <returns></returns>
        public int DeleteAll(string schoolMark)
        {
            Hashtable ht = new Hashtable();
            ht.Add("SchoolMark", schoolMark);
            return DeleteCustomer("QuestionItems.Delete", ht);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entityId"></param>
        /// <param name="schoolMark"></param>
        /// <returns></returns>
        public QuestionItems FindById(int entityId, string schoolMark)
        {
            Hashtable ht = new Hashtable();
            ht.Add("RID", entityId);
            ht.Add("SchoolMark", schoolMark);
            return FindCustomerByID<QuestionItems>("QuestionItems.FindById", ht);
        }

        /// <summary>
        /// 检索对象数量
        /// </summary>
        /// <param name="schoolMark"></param>
        /// <returns></returns>
        public int FindCount(string schoolMark)
        {
            Hashtable ht = new Hashtable();
            ht.Add("SchoolMark", schoolMark);
            return FindCustomerByCount("QuestionItems.FindCount", ht);
        }

        /// <sammury>
        /// 检索对象
        /// </sammury>
        /// <param name="schoolMark"></param>
        /// <returns></returns>
        public IList<QuestionItems> FindAll(string schoolMark)
        {
            Hashtable ht = new Hashtable();
            ht.Add("SchoolMark", schoolMark);
            return FindCustomer<QuestionItems>("QuestionItems.Find", ht);
        }

        /// <summary>
        /// 检索对象数量
        /// </summary>
        /// <returns></returns>
        public int FindCount(Hashtable table)
        {
            return FindObjectByCount(table);
        }

        /// <sammury>
        /// 检索对象
        /// </sammury>
        public IList<QuestionItems> FindAll(Hashtable table)
        {
            return FindObject(table);
        }

        #endregion

        #region IQuestionItemsLogic 成员

        public String GetOptStirng(String xml)
        {
            String optString = String.Empty;
            //xml = xml.Replace("&nbsp;", " ");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlElement root = doc.DocumentElement;
            XmlNodeList optionNodeList = root.GetElementsByTagName("opt");
            if (optionNodeList == null || optionNodeList.Count < 1)
                return null;

            foreach (XmlNode optNode in optionNodeList)
            {
                XmlElement optElm = optNode as XmlElement;
                XmlNodeList codeNodeList = optElm.GetElementsByTagName("index");
                XmlNodeList titleNodeList = optElm.GetElementsByTagName("TITLE");
                if (titleNodeList == null || titleNodeList.Count < 1)
                    titleNodeList = optElm.GetElementsByTagName("title");
                XmlNodeList scoreNodeList = optElm.GetElementsByTagName("score");

                optString += String.Format("{0}.{1}({2}分)  ", codeNodeList.Item(0).InnerText, titleNodeList.Item(0).InnerText, scoreNodeList.Item(0).InnerText);
            }

            return optString;
        }

        public int AddReq(QuestionItems obj, String schoolMark)
        {
            Hashtable ht = new Hashtable();
            ht.Add("QtTypeID", obj.QtTypeID);
            ht.Add("SchoolMark", schoolMark);
            IList<QuestionItems> reqClsList = this.FindAll(ht);
            if (reqClsList.Count < 1)
            {
                obj.QiPosition = 0;
            }
            else
            {
                int maxIndex = 0;
                foreach (QuestionItems req in reqClsList)
                {
                    maxIndex = Math.Max(req.QiPosition, maxIndex);
                }
                obj.QiPosition = maxIndex + 1;
            }

            return this.CreateQuestionItems(obj, schoolMark);
        }

        [Transaction(TransactionMode.Requires)]
        public int DeleteReqAndSort(int reqId, String schoolMark)
        {
            SortReqInClsWhenDeletedReq(reqId, schoolMark);
            return this.Delete(reqId, schoolMark);
        }

        [Transaction(TransactionMode.Requires)]
        public int ImportReqs(string list, int destReqClsId, String schoolMark)
        {
            String[] arr = list.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            Hashtable ht = new Hashtable();
            ht.Add("QtTypeID", destReqClsId);
            ht.Add("SchoolMark", schoolMark);
            IList<QuestionItems> reqList = this.FindAll(ht);
            int maxIndex = 0;
            if (reqList.Count < 1)
            {
                maxIndex = -1;
            }
            else
            {
                foreach (QuestionItems req in reqList)
                {
                    maxIndex = Math.Max(maxIndex, req.QiPosition);
                }
            }
            IList<Hashtable> needUpdateList = new List<Hashtable>();
            foreach (String id in arr)
            {
                QuestionItems req = this.FindById(Convert.ToInt32(id), schoolMark);
                req.QtTypeID = destReqClsId;
                req.QiPosition = maxIndex + 1;
                maxIndex++;
                Hashtable tht = new Hashtable();
                tht.Add("QuestionItems", req);
                tht.Add("SchoolMark", schoolMark);
                needUpdateList.Add(tht);
                //int i = Container<IReqLogic>.Instance.Create(req);
                //if (i > -1)
                //    result++;
                //SortReqInClsWhenDeletedReq(req.RID, schoolMark);
                //if(this.CreateQuestionItems(req, schoolMark) < 1)
                //    throw new Exception();
            }
            if (needUpdateList.Count > 0)
                BatchSave("QuestionItems.InsertQuestionItems", needUpdateList);

            return needUpdateList.Count;
        }

        public int MoveReq(int reqId, int destReqClsId, String schoolMark)
        {
            SortReqInClsWhenDeletedReq(reqId, schoolMark);

            QuestionItems obj = this.FindById(reqId, schoolMark);
            Hashtable ht = new Hashtable();
            ht.Add("QtTypeID", destReqClsId);
            ht.Add("SchoolMark", schoolMark);
            IList<QuestionItems> reqClsList = this.FindAll(ht);
            if (reqClsList.Count < 1)
            {
                obj.QiPosition = 0;
            }
            else
            {
                int maxIndex = 0;
                foreach (QuestionItems req in reqClsList)
                {
                    maxIndex = Math.Max(req.QiPosition, maxIndex);
                }
                obj.QiPosition = maxIndex + 1;
            }
            obj.QtTypeID = destReqClsId;

            return this.UpdateQuestionItems(obj, schoolMark);
        }

        [Transaction(TransactionMode.Requires)]
        public int MoveReqs(string list, int destReqClsId, String schoolMark)
        {
            int result = 0;
            result = ImportReqs(list, destReqClsId, schoolMark);
            result = DeleteReqs(list, schoolMark);
            return result;
        }

        [Transaction(TransactionMode.Requires)]
        public int DeleteReqs(string list, String schoolMark)
        {
            String[] arr = list.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            IList<QuestionItems> needUpdateList = new List<QuestionItems>();
            int result = 0;
            foreach (String id in arr)
            {
                result += this.DeleteReqAndSort(Convert.ToInt32(id), schoolMark);
            }
            return result;
        }

        /// <summary>
        /// 排序
        /// </summary>
        public int SortReq(int reqClsId, Hashtable ht, String schoolMark)
        {
            Hashtable htt = new Hashtable();
            htt.Add("QtTypeID", reqClsId);
            htt.Add("SchoolMark", schoolMark);
            IList<QuestionItems> reqList = this.FindAll(htt);
            IList<Hashtable> needUpdateList = new List<Hashtable>();
            foreach (QuestionItems item in reqList)
            {
                item.QiPosition = Convert.ToInt32(ht[item.RID.ToString()]);
                Hashtable tht = new Hashtable();
                tht.Add("QuestionItems", item);
                tht.Add("SchoolMark", schoolMark);
                needUpdateList.Add(tht);
            }
            return BatchUpdate("QuestionItems.UpdateQuestionItems", needUpdateList);
        }

        #endregion

        /// <summary>
        /// 当题目被移动或删除 重排同题目类别下的题目序号
        /// </summary>
        /// <param name="reqId"></param>
        /// <returns></returns>
        private int SortReqInClsWhenDeletedReq(int reqId, String schoolMark)
        {
            QuestionItems reqBean = this.FindById(reqId, schoolMark);
            Hashtable ht = new Hashtable();
            ht.Add("QtTypeID", reqBean.QtTypeID);
            ht.Add("SchoolMark", schoolMark);
            IList<QuestionItems> reqList = this.FindAll(ht);

            IList<Hashtable> needUpdateList = new List<Hashtable>();
            foreach (QuestionItems item in reqList)
            {
                if (item.QiPosition > reqBean.QiPosition)
                {
                    item.QiPosition -= 1;
                    Hashtable tht = new Hashtable();
                    tht.Add("QuestionItems", item);
                    tht.Add("SchoolMark", schoolMark);
                    needUpdateList.Add(tht);
                }
            }
            if (needUpdateList.Count > 0)
                BatchUpdate("QuestionItems.UpdateQuestionItems", needUpdateList);

            return needUpdateList.Count;
        }

        /// <summary>
        /// 插入题目类别
        /// </summary>
        public int CreateQuestionItems(QuestionItems questionItem, string schoolMark)
        {
            try
            {
                Hashtable ht = new Hashtable();
                ht.Add("QtTypeID", questionItem.QtTypeID);
                ht.Add("SchoolMark", schoolMark);
                IList<QuestionItems> reqClsList = this.FindAll(ht);
                if (reqClsList.Count < 1)
                {
                    questionItem.QiPosition = 0;
                }
                else
                {
                    int maxIndex = 0;
                    foreach (QuestionItems req in reqClsList)
                    {
                        maxIndex = Math.Max(req.QiPosition, maxIndex);
                    }
                    questionItem.QiPosition = maxIndex + 1;
                }

                questionItem.QiOpts = questionItem.QiOpts.Replace("&nbsp;", " ");
                ht = new Hashtable();
                ht.Add("QuestionItems", questionItem);
                ht.Add("SchoolMark", schoolMark);
                int id = (int)InsertCustomer("QuestionItems.InsertSingle", ht);
                return id;
            }
            catch (Exception e)
            {
                return -1;
            }
        }

        /// <summary>
        /// 更新题目类别
        /// </summary>
        public int UpdateQuestionItems(QuestionItems questionItem, string schoolMark)
        {
            try
            {
                questionItem.QiOpts = questionItem.QiOpts.Replace("&nbsp;", " ");
                Hashtable ht = new Hashtable();
                ht.Add("QuestionItems", questionItem);
                ht.Add("SchoolMark", schoolMark);

                int id = (int)UpdateCustomer("QuestionItems.UpdateQuestionItems", ht);
                return id;
            }
            catch (Exception)
            {
                return -1;
            }
        }

        /// <summary>
        /// 查询题目列表
        /// </summary>
        /// <param name="qtID"></param>
        /// <param name="schoolMark"></param>
        /// <returns></returns>
        public IList<QuestionItems> FindQuestionItems(int qtID, string schoolMark)
        {
            Hashtable ht = new Hashtable();
            ht.Add("QtTypeID", qtID);
            ht.Add("SchoolMark", schoolMark);
            return FindCustomer<QuestionItems>("QuestionItems.Find", ht);
        }
    }
}
